<template>
    <div class="search-container">
        <form action="/" class="search-from">
            <van-search v-model="searchText" placeholder="请输入搜索关键词" background="#3296fa" @search="onSearch"
                @cancel="onCancel" @focus="isResultShow = false" show-action />
        </form>
        <searchResult v-if="isResultShow" :search-text="searchText"></searchResult>
            <searchSuggestion v-else-if="searchText" :search-text="searchText" @search="onSearch"></searchSuggestion>
            <searchHistory 
            v-else :search-histories="searchHistories" 
            @clear-search-histories="searchHistories=[]" 
            @search="onSearch"
            ></searchHistory>
    </div>

</template>

<script>
import searchHistory from './components/search-history.vue'
import searchSuggestion from './components/search-suggestion.vue'
import searchResult from './components/search-result.vue'
import {getItem ,setItem} from '@/utils/storeage'
export default {
    name: 'SearchIndex',
    data() {
        return {
            searchText: '',
            isResultShow: false , //控制搜索结果的显示状态
            searchHistories:getItem('TOUTIAO_SEARCH_HISTORY') || []
        }
    },
    methods: {
        onSearch(val) {
            if(val.trim().length===0) return
            console.log(val)
            this.searchText = val
            const index = this.searchHistories.indexOf(val)
            if(index !== -1){
                this.searchHistories.splice(index,1)
            }
            this.searchHistories.unshift(val)
            this.isResultShow = true
        },
        onCancel() {
            this.$router.back()
        }
    },
    components: {
        searchHistory, searchSuggestion, searchResult
    },
    watch:{
        searchHistories(value){
            setItem('TOUTIAO_SEARCH_HISTORY',value)
        }
    }
}
</script>

<style scoped lang="less">
.search-container {
    padding-top: 108px;

    .van-search__action {
        color: #fff;
    }

    .search-from {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        z-index: 1;
    }
}
</style>